from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re
from .models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData


def get_user_by_account(account):
    try:
        # 判断账号是用户名还是手机
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        '''
        把下面直接定义成函数
        try:
            # 判断账号是用户名还是手机
            if re.match(r'^1[3-9]\d{9}]$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None

        '''

        user = get_user_by_account(username)

        if user and user.check_password(password):
            # 返回user对象
            return user

def generate_verify_email_url(user):
    """生成的邮箱需要加密"""
    serializer = Serializer(settings.SECRET_KEY, 60*60*24)
    data = {'user_id': user.id, 'email': user.email}
    token = serializer.dumps(data).decode()
    # 拼接激活的url
    verify_url= settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url

def check_verify_email_token(token):
    """接受前端传来的信息并提取token，返回user"""
    serializer = Serializer(settings.SECRET_KEY, 60 * 60 * 24)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user



